package com.example.remindme

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.example.register_demo.home.HomeFragment
import com.example.remindme.HomePages.userDatabase.DatabaseViewModel
import com.example.register_demo.home.LoginAndRegister.LoginFragment
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch


// 把loginactivity 作为启动activity
class LoginActivity:AppCompatActivity() {

    private lateinit var dataViewModel : DatabaseViewModel // 这里需要登录的数据库

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)



        dataViewModel= ViewModelProvider(this,
                ViewModelProvider.AndroidViewModelFactory(this.application)).get(DatabaseViewModel::class.java)

        GlobalScope.launch {
            dataViewModel.queryRemember()
        }
        initObserve()



    }

    private fun initObserve() {
        dataViewModel.finished.observe(this,{

            if(dataViewModel.rememberAccount?.isEmpty()==true)
            {

                val fragment= LoginFragment()
                supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentcontainer,fragment,"login")
                        .commit()
            }
            else
            {
                val homeFragment= HomeFragment()
                supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentcontainer,homeFragment,"home")
                        .commit()
                Toast.makeText(this,"Automatically login",Toast.LENGTH_SHORT).show()
            }
        })
    }

}